from paste.httpheaders import *
from paste.auth import digest

from pprint import pprint

def check_users(environ, realm, username):
    users = environ['digestmiddleware.users']
    for u, p in users.items():
        if username == u:
            return digest.digest_password(realm, u, p)

def do_auth(fn):
    def authenticator(obj, environ, start_response, *args, **kw):
        environ['digestmiddleware.users'] = obj.users
        authorizor = digest.AuthDigestAuthenticator(obj.realm, check_users)
        username = REMOTE_USER(environ)
        if not username:
            result = authorizor(environ)
            print result
            if isinstance(result, str):
                AUTH_TYPE.update(environ,'digest')
                REMOTE_USER.update(environ, result)
            else:
                return result.wsgi_application(environ, start_response)
        return fn(obj, environ, start_response, *args, **kw)
    return authenticator

def load_users(app_conf):
    if app_conf.get('digest_users_file'):
        f = file(app_conf['digest_users_file'])
        users = dict([ tuple(line.strip().split(':')) for line in  f])
        f.close()
        return users
    return None



# this is unused but is provided simply as a reference for creating
# custom middleware for digest authentication

class DigestMiddleware(object):

    def __init__(self, app_conf, app):
        if app_conf.get('digest_users_file'):
            f = file(app_conf['digest_users_file'])
            self.users = dict(
                [ tuple(line.split(':')) for line in  f]
            )
            f.close()
        self.realm = app_conf.get('digest_realm', 'Digest Authentication')
        self.app = app

    def do_auth(self, environ, start_response):
        username = REMOTE_USER(environ)
        if not username:
            result = authorizor(environ)
            if isinstance(result, str):
                AUTH_TYPE.update(environ,'digest')
                REMOTE_USER.update(environ, result)
            else:
                return result.wsgi_application
        return None

    def __call__(self, environ, start_response):
        authorizor = digest.AuthDigestAuthenticator(self.realm, check_users)
        redirect = self.do_auth(environ, start_response)
        if redirect:
            return redirect(environ, start_response)
        return self.app(environ, start_response)

